/*
 * Copyright (c) 2019.
 * http://www.ulabcare.com
 */

package com.mt.roll.core.runner;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jiff
 * @date 2019-08-27
 * @since 1.0
 */
public class MesApplicationRunner implements ApplicationRunner, DisposableBean {
    private final ApplicationContext applicationContext;

    private List<MesInitializer> initializers;

    @Autowired
    public MesApplicationRunner(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, MesInitializer> runnerMap = applicationContext.getBeansOfType(MesInitializer.class);
        initializers = runnerMap.values().stream().sorted(Comparator.comparing(MesInitializer::order))
                .collect(Collectors.toList());

        for (MesInitializer mesInitializer : initializers) {
            mesInitializer.init();
        }
    }

    @Override
    public void destroy() throws Exception {
        for (MesInitializer mesInitializer : initializers) {
            mesInitializer.destroy();
        }
    }
}
